package com.kis.core;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import main.Server;

public class Utils {
	public static String readProperties(String key) {
		String value = "";
		Properties props = new Properties();
		InputStream in;
		try {
			in = Utils.class.getResourceAsStream("/rmi.properties");
			if(null!=in){
			props.load(in);
			value = props.getProperty(key);
			}else{
				throw new RuntimeException("找不到rmi.properties文件");
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if(value==""){
			throw new RuntimeException("找不到key："+key);
		}
		return value;
	}

	public static List<String> assService(String packagePath, boolean isFirst) {
		List<String> services = new ArrayList<String>();
		String mainPath = Server.class.getResource("").toString()
				.replace("file:/", "").replace("%20", "");
		String root = "";
		if (isFirst) {
			root = mainPath.substring(0, mainPath.indexOf("classes") + 8);
		} else {
			root = "";
		}
		if (mainPath.indexOf("classes") != -1) {
			String path = packagePath.replace(".", "/");
			File f = new File(root + path);
			if (f.canExecute() && f.isDirectory()) {
				for (File file : f.listFiles()) {
					List<String> deepService = new ArrayList<String>();
					if (file.isDirectory()) {
						deepService = assService(file.getAbsolutePath(), false);
						services.addAll(deepService);
					} else {
						String className = file.getName().substring(0,
								file.getName().indexOf("class") - 1);
						if (!className.endsWith("Impl")) {
							if (!file.getParentFile().getName()
									.startsWith("service")) {
								services.add(file.getParentFile().getName()
										+ "." + className);
							}
						}
					}
				}
			}
		} else {
			throw new RuntimeException("没有找到路径");
		}
		return services;
	}

	public static String visitPath(String path) {
		String visitPath = "";
		if (path.indexOf(".") > 0) {
			visitPath = firstToLower(path.split("\\.")[path.split("\\.").length - 1]);
		} else {
			visitPath = firstToLower(path);
		}
		return visitPath;
	}

	public static String firstToLower(String word) {
		String newString = "";
		if (null != word && word.length() > 0) {
			newString = word.substring(0, 1).toLowerCase()
					+ word.substring(1, word.length());
		}
		return newString;
	}
}
